package com.xyzwps.xgments.bit;

public class ReverseBits {

    private static final int[] BITS = new int[]{
            0, // 占位符
            0b00000000_00000000_00000000_00000001,
            0b00000000_00000000_00000000_00000010,
            0b00000000_00000000_00000000_00000100,
            0b00000000_00000000_00000000_00001000,
            0b00000000_00000000_00000000_00010000,
            0b00000000_00000000_00000000_00100000,
            0b00000000_00000000_00000000_01000000,
            0b00000000_00000000_00000000_10000000,

            0b00000000_00000000_00000001_00000000,
            0b00000000_00000000_00000010_00000000,
            0b00000000_00000000_00000100_00000000,
            0b00000000_00000000_00001000_00000000,
            0b00000000_00000000_00010000_00000000,
            0b00000000_00000000_00100000_00000000,
            0b00000000_00000000_01000000_00000000,
            0b00000000_00000000_10000000_00000000,

            0b00000000_00000001_00000000_00000000,
            0b00000000_00000010_00000000_00000000,
            0b00000000_00000100_00000000_00000000,
            0b00000000_00001000_00000000_00000000,
            0b00000000_00010000_00000000_00000000,
            0b00000000_00100000_00000000_00000000,
            0b00000000_01000000_00000000_00000000,
            0b00000000_10000000_00000000_00000000,

            0b00000001_00000000_00000000_00000000,
            0b00000010_00000000_00000000_00000000,
            0b00000100_00000000_00000000_00000000,
            0b00001000_00000000_00000000_00000000,
            0b00010000_00000000_00000000_00000000,
            0b00100000_00000000_00000000_00000000,
            0b01000000_00000000_00000000_00000000,
            0b10000000_00000000_00000000_00000000,
    };

    // you need treat n as an unsigned value
    public int reverseBits2(int n) {
        int result = 0;
        for (int i = 1; i <= 32; i++) {
            if ((n & BITS[i]) != 0) {
                result |= BITS[33 - i];
            }
        }
        return result;
    }

    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int result = 0;
        for (int i = 1; i <= 32; i++) {
            int bit = n & 0b1;
            result <<= 1;
            result |= bit;
            n >>= 1;
        }
        return result;
    }

    public static void main(String[] args) {
        ReverseBits rb = new ReverseBits();
        System.out.println(Integer.toBinaryString(rb.reverseBits(0)));
        System.out.println(Integer.toBinaryString(rb.reverseBits(0b00000010100101000001111010011100)));
        System.out.println(Integer.toBinaryString(rb.reverseBits2(0)));
        System.out.println(Integer.toBinaryString(rb.reverseBits2(0b00000010100101000001111010011100)));
    }
}
